//
//  YHTransactionLookSubAViewController.m
//  YHApp
//
//  Created by -- on 2021/6/29.
//

#import "HATransactionLookSubAVC.h"
#import "HATransactionLookListMo.h"
#import "HATransactionLookSubTableViewCell.h"
#import "HATransactionLookDVC.h"
#import "HATransactionLookScreenPopView.h"

@interface HATransactionLookSubAVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
/***/
@property (nonatomic, strong) UITextField *seachField;

/***/
@property (nonatomic, strong) NSString *keyword;
/***/
@property (nonatomic, strong) NSString *start;
/***/
@property (nonatomic, strong) NSString *end;
/***/
@property (nonatomic, strong) NSString *type;
/***/
@property (nonatomic, strong) NSString *state;

/***/
@property (nonatomic, strong) UILabel *num1Label;
/***/
@property (nonatomic, strong) UILabel *tit1Label;
/***/
@property (nonatomic, strong) UILabel *num2Label;
/***/
@property (nonatomic, strong) UILabel *tit2Label;
/***/
@property (nonatomic, strong) UILabel *num3Label;
/***/
@property (nonatomic, strong) UILabel *tit3Label;

@end

@implementation HATransactionLookSubAVC
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    MJRefreshGifHeader *mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header = mj_header;
    
    MJRefreshBackGifFooter *mj_footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(laodMoreData)];
    self.tableView.mj_footer = mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
    
    // Do any additional setup after loading the view.
}

-(void)setupUI {
    
    UIView *seachBgView = [UIView ha_createView];
    seachBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:seachBgView];
    [seachBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_offset(44);
    }];
    
    UIButton *moreBtn = [[UIButton alloc]init];
    [moreBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];


    UIButton *seachBtn = [[UIButton alloc]init];
    [seachBtn setImage:[UIImage xl_cuttingImageWith:[UIImage imageNamed:@"ha_searchIcon"] toSize:CGSizeMake(22, 22)] forState:UIControlStateNormal];
    [seachBtn addTarget:self action:@selector(seachBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:seachBtn];
    [seachBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(moreBtn.mas_left).offset(-5);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];

    UITextField *seachField = [[UITextField alloc]init];
    self.seachField = seachField;
    seachField.delegate = self;
    seachField.placeholder = @"请输入机具编号/商户名称";
    seachField.font = [UIFont systemFontOfSize:18];
    seachField.returnKeyType = UIReturnKeySearch;
    [seachBgView addSubview:seachField];
    [seachField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.equalTo(seachBtn.mas_left).offset(-15);
        make.centerY.mas_equalTo(0);
        make.height.equalTo(@32);
    }];
    
    ///统计
    UIView *mod1View = [self getModView:1];
    mod1View.backgroundColor = [UIColor colorWithHexString:@"#4876F1"];
    [self.view addSubview:mod1View];
    [mod1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.top.mas_equalTo(54);
        make.height.mas_offset(60);
        make.width.mas_offset((kUIScreen_w-48)/3);
    }];
    UIView *mod2View = [self getModView:2];
    mod2View.backgroundColor = [UIColor colorWithHexString:@"#6AE176"];
    [self.view addSubview:mod2View];
    [mod2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(54);
        make.height.mas_offset(60);
        make.width.mas_offset((kUIScreen_w-48)/3);
    }];
    UIView *mod3View = [self getModView:3];
    mod3View.backgroundColor = [UIColor colorWithHexString:@"#E95D5E"];
    [self.view addSubview:mod3View];
    [mod3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-12);
        make.top.mas_equalTo(54);
        make.height.mas_offset(60);
        make.width.mas_offset((kUIScreen_w-48)/3);
    }];

    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(54+60);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

-(UIView *)getModView:(NSInteger)type {
    UIView *view = [UIView ha_createView];
    
    UILabel *titLabel = [UILabel ha_NLabelWithFont:12 textColor:@"#ffffff" text:@"0" alignment:1];
    [view addSubview:titLabel];
    [titLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(14);
        make.height.mas_offset(14);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    UILabel *numLabel = [UILabel ha_NLabelWithFont:14 textColor:@"#ffffff" text:@"0" alignment:1];
    [view addSubview:numLabel];
    [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(-14);
        make.height.mas_offset(14);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    if (type == 1) {
        self.num1Label = numLabel;
        titLabel.text = @"交易金额";
        self.tit1Label = titLabel;
    }
    if (type == 2) {
        self.num2Label = numLabel;
        titLabel.text = @"结算金额";
        self.tit2Label = titLabel;
    }
    if (type == 3) {
        self.num3Label = numLabel;
        titLabel.text = @"总手续费";
        self.tit3Label = titLabel;
    }
    
    return view;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54+32+10+22;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HATransactionLookSubTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HATransactionLookSubTableViewCellID"];
    if (!cell) {
        cell = [[HATransactionLookSubTableViewCell alloc]initWithStyle:0 reuseIdentifier:@"HATransactionLookSubTableViewCellID"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HATransactionLookListMo *model = self.dataArray[indexPath.row];
    HATransactionLookDVC *vc = [[HATransactionLookDVC alloc]init];
    vc.trade_id = model.trade_id;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)seachBtnClick {
    if ([NSString isEmptyString:self.seachField.text]) {
        [MBProgressHUD showError:@"请输入机具编号/商户名称"];
        return;
    }
    
    self.keyword = self.seachField.text;
    
    [self.tableView.mj_header beginRefreshing];

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self.view endEditing:YES];
    
    if (textField == self.seachField) {
        if ([NSString isEmptyString:self.seachField.text]) {
            [MBProgressHUD showError:@"请输入机具编号/商户名称"];
            return NO;
        }
        
        self.keyword = textField.text;
        
        [self.tableView.mj_header beginRefreshing];
    }

    return YES;
}

-(void)moreBtnClick{
    WS(weakSelf)
    HATransactionLookScreenPopView *menu = [[HATransactionLookScreenPopView alloc]init];
    menu.keyword = self.keyword;
    menu.start = self.start;
    menu.end =self.end;
    menu.state = self.state;
    menu.type = self.type;
    [menu show];
    menu.HATransactionLookScreenPopViewBlock = ^(NSString * _Nonnull searchText, NSString * _Nonnull start, NSString * _Nonnull end, NSString * _Nonnull type, NSString * _Nonnull state) {
        weakSelf.keyword = searchText;
        weakSelf.seachField.text = searchText;
        weakSelf.start = start;
        weakSelf.end = end;
        weakSelf.type = type;
        weakSelf.state = state;
        [weakSelf.tableView.mj_header beginRefreshing];
    };
    menu.HATransactionLookScreenPopViewResetBlock = ^{
        weakSelf.keyword = @"";
        weakSelf.seachField.text = @"";
        weakSelf.start = @"";
        weakSelf.end = @"";
        weakSelf.type = @"";
        weakSelf.state = @"";
        [weakSelf.tableView.mj_header beginRefreshing];
    };
}

-(void)loadNewData {
    
    NSDictionary *dict = @{
        @"pageSize":@"10",
        @"page":@"1",
        @"source_id":self.canalItemModel.value?:@"",
        @"keyword":self.keyword?:@"",
        @"start":self.start?:@"",
        @"end":self.end?:@"",
        @"type":self.type?:@"",
        @"state":self.state?:@"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"trade/items.html"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;

    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_header endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [self.dataArray removeAllObjects];
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HATransactionLookListMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
                if ([[dataModel.data allKeys]containsObject:@"totalItems"]) {
                    NSArray *totalItems = dataModel.data[@"totalItems"];
                    if (totalItems.count > 0) {
                        NSDictionary *dic = totalItems[0];
                        self.tit1Label.text = dic[@"label"];
                        self.num1Label.text = [NSString stringWithFormat:@"%@",dic[@"number"]];
                    }
                    if (totalItems.count > 1) {
                        NSDictionary *dic = totalItems[1];
                        self.tit2Label.text = dic[@"label"];
                        self.num2Label.text = [NSString stringWithFormat:@"%@",dic[@"number"]];
                    }
                    if (totalItems.count > 2) {
                        NSDictionary *dic = totalItems[2];
                        self.tit3Label.text = dic[@"label"];
                        self.num3Label.text = [NSString stringWithFormat:@"%@",dic[@"number"]];
                    }
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
            
        }
    }];
    
}

-(void)laodMoreData {
    
    NSInteger count = ceilf(self.dataArray.count*0.1)+1;
    NSString *pageNo = [NSString stringWithFormat:@"%ld",(long)count];
    
    NSDictionary *dict = @{
        @"pageSize":@"10",
        @"page":pageNo,
        @"source_id":self.canalItemModel.value?:@"",
        @"keyword":self.keyword?:@"",
        @"start":self.start?:@"",
        @"end":self.end?:@"",
        @"type":self.type?:@"",
        @"state":self.state?:@"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"trade/items.html"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;

    [self.tableView.mj_footer beginRefreshing];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_footer endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HATransactionLookListMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
        }
    }];
    
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



#pragma mark - 无数据处理 DZNEmptyDataSetSource DZNEmptyDataSetDelegate
//设置title
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无数据~";
    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#999999"]
    };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

//设置image
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"hl_nodata"];
}

@end
